<template>
	<view class="container position-relative">
		<view class="custom-nav">
			<image src="/static/images/back.png" style="width: 40rpx; height: 40rpx" @tap="goToHome"></image>
		</view>
		<view style="margin-bottom: 130rpx">
			<!-- 订单状态提示 -->
			<view v-if="order_no" class="order-status font-size-sm text-color-assist">
				订单号: {{ order_no }} ({{ order_status_text }})
			</view>
			<!-- 地址信息 -->
			<view class="section-1">
				<list-cell>
					<view class="d-flex align-items-center justify-content-between mb-10">
						<image src="/static/images/map.png" class="scan-icon-left"></image>
					</view>
					<view class="w-100 d-flex flex-column" style="margin-left: 10rpx; font-size: 32rpx">
						<view class="d-flex align-items-center justify-content-between mb-10 input-item">
							<input class="input-field" type="text" v-model="address.name" placeholder="请输入姓名"
								maxlength="20" />
							<input class="input-field" type="number" v-model="address.mobile" placeholder="请输入手机号"
								maxlength="11" />
						</view>
						<view class="d-flex" style="margin-top: 8rpx; font-size: 28rpx">
							<view class="address-info text-color-assist font-size-base" v-if="address.scanAddress">
								{{ address.scanAddress }}</view>
							<view class="font-size-lg text-color-base" v-else>请扫码获取地址</view>
						</view>
					</view>
					<view class="d-flex" @click="scanToGetAddress">
						<image src="/static/images/scan-icon.png" class="scan-icon-left"></image>
					</view>
				</list-cell>
			</view>

			<!-- 餐厅信息 -->
			<view class="section-1">
				<list-cell class="location">
					<view class="flex-fill d-flex justify-content-between align-items-center">
						<view class="store-name flex-fill">店铺：<span
								style="color: #289365">{{ store.name }}{{ table.name ? "-" + table.name : "" }}</span>
						</view>
					</view>
				</list-cell>
				<list-cell>
					<view class="w-100 d-flex flex-column">
						<view class="d-flex align-items-center font-size-base text-color-base">
							<view class="flex-fill">如对该订单有疑问请致电管理人员：</view>
							<view class="font-size-base">
								<view class="mr-10">
									{{ store.contacts }}
								</view>
								<view class="mr-10">
									{{ store.phone }}
								</view>
							</view>
						</view>
					</view>
				</list-cell>
			</view>

			<!-- 购物车列表 -->
			<view class="section-2">
				<view class="cart d-flex flex-column">
					<list-cell last v-for="(item, index) in cart" :key="index">
						<view class="w-100 d-flex flex-column">
							<view class="d-flex align-items-center mb-10">
								<view
									class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg">
									<image style="width: 80rpx; height: 80rpx" mode="aspectFill" :src="item.image">
									</image>
								</view>
								<view class="name-and-props overflow-hidden">
									<view class="text-color-base font-size-lg">{{
                    item.name
                  }}</view>
								</view>
								<view
									class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg">
									<view>x{{ item.number }}</view>
									<view>￥{{ item.sales_price }}</view>
								</view>
							</view>
							<view class="text-truncate font-size-base text-color-assist">{{
                item.props_text
              }}</view>
						</view>
					</list-cell>
				</view>
				<list-cell last>
					<view class="flex-fill d-flex justify-content-end align-items-center">
						<view>
							总计￥{{ total }}
							<text v-if="coupon.value">,￥-{{ coupon.value }}</text>, 实付
						</view>
						<view class="font-size-extra-lg font-weight-bold">￥{{ amount }}</view>
					</view>
				</list-cell>
			</view>

			<!-- 支付方式 -->
			<view class="payment">
				<list-cell last :hover="false"><text>支付方式</text></list-cell>
				<list-cell>
					<view class="d-flex align-items-center justify-content-between w-100"
						:class="{ disabled: parseFloat(member.money) < parseFloat(amount) }" @click="setPayType(2)">
						<view class="iconfont iconbalance line-height-100 payment-icon"></view>
						<view class="flex-fill">余额支付（账户余额￥{{ member.money }}）</view>
						<view class="font-size-sm" v-if="parseFloat(member.money) < parseFloat(amount)">余额不足</view>
						<view class="iconfont line-height-100 checkbox checked iconradio-button-on" v-if="payType == 2">
						</view>
						<view class="iconfont line-height-100 checkbox iconradio-button-off" v-else></view>
					</view>
				</list-cell>
				<list-cell last>
					<view class="d-flex align-items-center justify-content-between w-100" @click="setPayType(1)">
						<view class="iconfont iconwxpay line-height-100 payment-icon" style="color: #7eb73a"></view>
						<view class="flex-fill">微信支付</view>
						<view class="iconfont line-height-100 checkbox checked iconradio-button-on" v-if="payType == 1">
						</view>
						<view class="iconfont line-height-100 checkbox iconradio-button-off" v-else></view>
					</view>
				</list-cell>
			</view>

			<!-- 备注 -->
			<list-cell arrow last @click="goToRemark">
				<view class="d-flex flex-fill align-items-center justify-content-between overflow-hidden">
					<view class="flex-shrink-0 mr-20">备注</view>
					<view class="text-color-primary flex-fill text-truncate text-right">{{
            remark || "点击填写备注"
          }}</view>
				</view>
			</list-cell>

			<!-- 付款栏 -->
			<view style="z-index: 1; margin-bottom: 50rpx"
				class="w-100 pay-box position-fixed fixed-bottom d-flex align-items-center justify-content-between bg-white">
				<view class="font-size-sm" style="margin-left: 20rpx">合计：</view>
				<view class="font-size-lg flex-fill">￥{{ amount }}</view>
				<view
					class="bg-primary h-100 d-flex align-items-center just-content-center text-color-white font-size-base"
					style="padding: 0 60rpx" @tap="$u.debounce(submit, 500)">立即付款</view>
			</view>

			<!-- 确认模态框 -->
			<modal :show="ensureAddressModalVisible" custom :mask-closable="false" :radius="'20rpx'" width="90%">
				<view class="modal-content">
					<view class="d-flex justify-content-end">
						<image src="/static/images/pay/close.png" style="width: 40rpx; height: 40rpx"
							@tap="ensureAddressModalVisible = false"></image>
					</view>
					<view class="d-flex just-content-center align-items-center" style="margin-bottom: 40px">
						<view class="font-size-extra-lg text-color-base">请确认地址信息</view>
					</view>
					<view
						class="d-flex font-size-base text-color-base font-weight-bold align-items-center justify-content-between mb-20">
						<view>姓名：{{ address.name }} {{ address.sex ? "女士" : "先生" }}</view>
						<view>电话：{{ address.mobile }}</view>
					</view>
					<view
						class="d-flex font-size-base  text-color-base font-weight-bold align-items-center justify-content-between mb-20">
						<view>配送地址：{{ address.scanAddress }}</view>
						<!-- <button
              type="primary"
              size="mini"
              plain
              class="change-address-btn"
              style="white-space: nowrap"
              @click="scanToGetAddress"
            >
              重新扫码
            </button> -->
					</view>
					<button type="primary" class="pay_btn" @tap="$u.debounce(pay, 500)">
						确认并付款
					</button>
				</view>
			</modal>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations,
		mapGetters
	} from "vuex";
	import listCell from "@/components/list-cell/list-cell";
	import modal from "@/components/modal/modal";
	// #ifdef H5
	var jweixin = require("jweixin-module");
	// #endif

	export default {
		components: {
			listCell,
			modal
		},
		data() {
			return {
				cart: [],
				remark:'',
				ensureAddressModalVisible: false,
				takeoutTIme: false,
				paramsTime: {
					year: false,
					month: false,
					day: false,
					hour: true,
					minute: true,
					second: false,
				},
				defaultTime: "00:00",
				takeinTIme: false,
				takeinRange: [],
				defaultSelector: [0],
				payType: 1, // 1=微信支付, 2=余额支付
				coupons: 0,
				coupon: {},
				subscribeMss: {
					takein: "",
					takeout: "",
					takein_made: "",
					takeout_made: "",
				},
				address: {
					name: "",
					mobile: "",
					sex: 0,
					scanAddress: "",
					address_id: "",
				},
				cart_ids: [],
				order_no: "", // 存储订单号
				order_status: 0, // 订单状态
				order_status_text: "", // 订单状态文本
			};
		},
		computed: {
			...mapState(["orderType", "store", "member", "table"]),
			total() {
				return this.cart.reduce(
					(acc, cur) => acc + cur.number * cur.sales_price,
					0
				);
			},
			amount() {
				let amount = this.total;
				if (this.coupon.hasOwnProperty("id")) {
					amount -= parseFloat(this.coupon.value);
				}
				return amount.toFixed(2);
			},
		},
		onShow() {
			let date = new Date(new Date().getTime() + 3600000);
			let hour = date.getHours();
			let minute = date.getMinutes();
			if (hour < 10) hour = "0" + hour;
			if (minute < 10) minute = "0" + minute;
			this.defaultTime = hour + ":" + minute;
			this.payType = uni.getStorageSync("paytype") || 1;
			this.getUserInfo();
			   let pages = getCurrentPages();
			       let currPage = pages[pages.length-1];
			       if (currPage.data.remark){
					   this.remark=currPage.data.remark
			            console.log(currPage.data.remark);//接收的数据
			       }
		},
		onLoad(option = {}) {
			console.log(option)
			const {
				address_detail
			} = option;
			this.cart = uni.getStorageSync("cart") || [];
			// if (remark) this.$set(this.form, "remark", remark);
			if (address_detail) {
				this.address.scanAddress = decodeURIComponent(address_detail);
				this.address.address_id = decodeURIComponent(address_detail);
			}
			this.addCartItemsToBackend();
		},
		// onBackPress() {
		// 	console.log(123213)
		// 	uni.switchTab({
		// 		url: '/pages/index/index'
		// 	})
		// },
		// onUnload(){
		// 	uni.switchTab({
		// 		url: '/pages/index/index'
		// 	})
		// },
		
		
		methods: {
			...mapMutations(["SET_ORDER_TYPE", "SET_MEMBER"]),
			...mapGetters(["isLogin"]),
			async addCartItemsToBackend() {
				if (!this.cart.length) {
					this.$u.toast("购物车为空，请重新选择商品");
					uni.navigateBack();
					return;
				}
				uni.showLoading({
					title: "同步购物车中"
				});
				try {
					this.cart_ids = [];
					for (const item of this.cart) {
						const data = {
							goods_id: item.id,
							num: item.number,
							type: 0
						};
						const response = await this.$u.api.addOrderCart(data);
						if (response.error === 1) {
							this.$u.toast("购物车商品类别不匹配，请重新选择");
							uni.navigateBack();
							return;
						}
						if (response && response.cart_id) {
							this.cart_ids.push(response.cart_id);
						}
					}
					uni.hideLoading();
				} catch (error) {
					uni.hideLoading();
					this.$u.toast("加入购物车失败，请返回重新选择");
					uni.navigateBack();
				}
			},
			async getUserInfo() {
				if (this.isLogin) {
					let data = await this.$u.api.userGetUserInfo();
					if (data) {
						this.SET_MEMBER({
							...this.member,
							money: data.money
						});
						if (data.real_name) this.address.name = data.real_name;
						if (data.mobile) this.address.mobile = data.mobile;
						if (data.address) this.address.scanAddress = data.address;
						if (data.address) this.address.address_id = data.address;
					}
				}
			},
			fillContact() {
				if (this.isLogin) {
					let data = this.member;
					if (data.name) this.address.name = data.name;
					if (data.mobile) this.address.mobile = data.mobile;
				}
			},
			setPayType(paytype) {
				if (paytype === 2 && parseFloat(this.member.money) < parseFloat(this.amount)) {
					this.$u.toast("余额不足，请选择其他支付方式");
					return;
				}
				this.payType = paytype;
				uni.setStorageSync("paytype", paytype);
			},
			goToRemark() {
				uni.navigateTo({
					url: "/pages/components/pages/remark/remark?remark=" +
						this.remark,
				});
			},
			parseUrlParams(url) {
				const params = {};
				if (!url || !url.includes("?")) {
					return params;
				}
				const queryStr = url.split("?")[1];
				if (!queryStr) {
					return params;
				}
				const paramPairs = queryStr.split("&");
				paramPairs.forEach(pair => {
					const [key, ...valueParts] = pair.split("=");
					const value = valueParts.join("=");
					if (!key) {
						return;
					}
					params[key] = decodeURIComponent(value || "");
				});
				return params;
			},
			scanToGetAddress() {
				let that = this;
				that.address = {
					...that.address,
					scanAddress: "",
					address_id: ""
				};

				uni.scanCode({
					onlyFromCamera: true,
					scanType: ["barCode", "qrCode"],
					success: async function(res) {
						uni.hideLoading();
						try {
							const scanResult = res.result?.trim() || "";
							if (!scanResult) {
								that.$u.toast("扫码结果为空，请重新扫描");
								return;
							}
							console.log("原始扫码结果：", scanResult);
							const params = that.parseUrlParams(scanResult);
							console.log("解析后的参数：", params);
							const bedParam = params.bed || "";
							const cleanBedParam = bedParam.includes("hospital_id=") ?
								bedParam.split("hospital_id=")[1] :
								bedParam;
							const hospitalId = params.H || params.hospital_id || "1";
							if (!cleanBedParam || cleanBedParam.length < 3 || /^\d+$/.test(cleanBedParam)) {
								that.$u.toast("二维码中未包含有效床位信息");
								console.warn("无效bed参数：", cleanBedParam);
								return;
							}
							if (hospitalId && hospitalId !== that.store.hospital_id) {
								that.$u.toast("扫码地址非本院区，请重新选择商品");
								console.warn("院区不匹配：扫码院区ID=" + hospitalId + "，当前店铺院区ID=" + that.store
									.hospital_id);
								return;
							}
							that.address.scanAddress = cleanBedParam;
							that.address.address_id = cleanBedParam;

							// 顺便调用 addressAdd 接口保存床位地址，不处理返回结果
							const addressData = {
								address: cleanBedParam,
								hospital_id: hospitalId,
								name: that.address.name || "",
								mobile: that.address.mobile || "",
							};
							that.$u.api.addressAdd(addressData).catch(error => {
								console.error("保存床位地址失败：", error);
								// 不提示错误，继续页面逻辑
							});

						} catch (e) {
							console.error("扫码解析失败：", {
								error: e,
								scanResult: res.result
							});
							that.$u.toast("扫码解析失败，请检查二维码格式");
						}
					},
					fail: function(err) {
						uni.hideLoading();
						console.error("扫码操作失败：", err);
						if (err.errMsg !== "scanCode:fail cancel") {
							that.$u.toast("扫码操作失败，请重试");
						}
					},
					complete: function() {
						uni.hideLoading();
					}
				});
			},

			submit() {
				if (!this.address.name) {
					this.$u.toast("请输入姓名");
					return;
				}
				if (!this.address.mobile) {
					this.$u.toast("请输入手机号");
					return;
				}
				if (!this.address.address_id) {
					this.$u.toast("请扫码获取地址");
					return;
				}
				if (this.address.address_id.length <= 1) {
					this.$u.toast("地址格式无效，请重新扫码获取");
					return;
				}
				if (!this.cart.length || !this.cart_ids.length) {
					this.$u.toast("购物车为空，请重新下单");
					uni.navigateBack();
					return;
				}
				this.ensureAddressModalVisible = true;
			},
			async pay() {
				uni.showLoading({
					title: "加载中"
				});
				try {
					// 如果已有订单号，检查订单状态
					if (this.order_no && this.order_no.trim() !== "") {
						const orderDetail = await this.$u.api.orderDetail({
							order_no: this.order_no,
						});
						if (orderDetail && orderDetail[0]) {
							this.order_status = orderDetail[0].status;
							this.order_status_text = orderDetail[0].status_text || "待支付";
							if (orderDetail[0].status !== 1) {
								this.$u.toast("订单已支付或状态异常");
								uni.switchTab({
									url: "/pages/take-foods/take-foods"
								});
								return;
							}
						}
					}
					// 如果没有订单号，创建新订单
					if (!this.order_no || this.order_no.trim() === "") {
						const data = {
							cart_ids: this.cart_ids.join(","),
							address_id: this.address.address_id,
							order_remark: this.remark || "",
							pay_type: this.payType, // 1=微信支付, 2=余额支付
							type: this.orderType === "takeout" ? 2 : 1, // 1=员工, 2=病人
							name: this.address.name,
							tel: this.address.mobile,
						};
						console.log("Submitting order:", data);
						let order = await this.$u.api.orderSubmit(data);
						console.log("Order response:", order);
						if(order.code===500){
							this.$u.toast(order.info);
							return false
						}
						
						if (!order) {
							throw new Error(order.msg || "订单创建失败");
						}

						if (order.order_no) {
							this.order_no = order.order_no;
							this.order_status = 1;
							this.order_status_text = "待支付";
						} else if (order.pay_code && order.pay_code == "202") {
							this.$u.toast("余额不足，切换到微信支付");
							this.payType = 1;
							await new Promise((resolve, reject) => {
								uni.requestPayment({
									provider: "wxpay",
									timeStamp: order.data.timeStamp,
									nonceStr: order.data.nonceStr,
									package: order.data.package,
									signType: "MD5",
									paySign: order.data.paySign,
									success: (res) => {
										this.handlePaymentSuccess();
										resolve(res);
									},
									fail: (err) => {
										if (err) {
											this.$u.toast("支付已取消");
											uni.switchTab({
												url: "/pages/take-foods/take-foods"
											});
										} else {
											this.$u.toast("支付失败，请重新支付");
										}
										reject(new Error("支付已取消"));
									},
									complete: (res) => {
										console.log("WeChat payment complete:", res);
										if (res && res.errMsg && res.errMsg.includes("cancel")) {
											this.$u.toast("支付已取消");
											uni.switchTab({
												url: "/pages/take-foods/take-foods"
											});
										}
									},
								});
							});
						}

						if (this.payType === 1) {
							await this.weixinPay(order.order_no);
						} else if (this.payType === 2) {
							if (order.pay_status === "1") {
								this.handlePaymentSuccess();
							} else {
								this.$u.toast("支付失败，请重新支付");
							}
						}
					}
				} catch (error) { 
					console.error("Pay error:", error);
					this.$u.toast(error.data.info || "操作失败，请重试");
				} finally {
					uni.hideLoading();
				}
			},
			async weixinPay(orderNo) {
				try {
					let data = await this.$u.api.payUnify({
						order_no: orderNo,
						pay_type: 1,
						name: this.address.name,
						tel: this.address.mobile,
						address_id: this.address.address_id,
						order_remark: this.remark || "",
					});
					if (!data) {
						throw new Error(data.msg || "微信支付调用失败");
					}
					if (
						!data.timeStamp ||
						!data.nonceStr ||
						!data.package ||
						!data.paySign
					) {
						throw new Error("微信支付参数缺失");
					}
					await new Promise((resolve, reject) => {
						uni.requestPayment({
							provider: "wxpay",
							timeStamp: data.timeStamp,
							nonceStr: data.nonceStr,
							package: data.package,
							signType: "MD5",
							paySign: data.paySign,
							success: (res) => {
								this.handlePaymentSuccess();
								resolve(res);
							},
							fail: (err) => {
								if (err) {
									this.$u.toast("支付已取消");
									uni.switchTab({
										url: "/pages/take-foods/take-foods"
									});
								} else {
									this.$u.toast("支付失败，请重新支付");
								}
								reject(new Error("支付已取消"));
							},
							complete: (res) => {
								console.log("WeChat payment complete:", res);
								if (res && res.errMsg && res.errMsg.includes("cancel")) {
									this.$u.toast("支付已取消");
									uni.switchTab({
										url: "/pages/take-foods/take-foods"
									});
								}
							},
						});
					});
				} catch (error) {
					console.error("WeChat pay error:", error);
					throw new Error(error.message || "微信支付调用失败");
				}
			},
			handlePaymentSuccess() {
				this.SET_MEMBER({
					...this.member,
					money: this.member.money - (this.payType === 2 ? this.amount : 0),
				});
				uni.removeStorageSync("cart");
				this.$u.toast("支付成功");
				this.order_no = "";
				uni.switchTab({
					url: "/pages/take-foods/take-foods"
				});
			},
			goToHome() {
				console.log(444)
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			takeinCancelTime() {
				this.takeinTIme = false;
			},
			takeinConfirmTime(e) {
				this.defaultSelector = e.index;
				this.takeinTIme = false;
			},
		},
	};
</script>

<style lang="scss" scoped>
	.container {
		padding: 30rpx;
	}

	.order-status {
		padding: 20rpx;
		background: #f5f5f5;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
	}

	.arrow {
		width: 50rpx;
		height: 50rpx;
		position: relative;
		margin-right: -10rpx;
	}

	.location {
		.store-name {
			font-size: $font-size-lg;
		}

		.iconfont {
			font-size: 50rpx;
			line-height: 100%;
			color: $color-primary;
		}
	}

	.section-1 {
		margin-bottom: 30rpx;

		.contact {
			.contact-tip {
				margin-left: 10rpx;
				border: 2rpx solid $color-primary;
				padding: 6rpx 10rpx;
				color: $color-primary;
			}
		}
	}

	.section-2 {
		.name-and-props {
			width: 65%;
		}
	}

	.payment {
		margin-bottom: 30rpx;

		.disabled {
			color: $text-color-grey;
		}

		.payment-icon {
			font-size: 44rpx;
			margin-right: 10rpx;
		}

		.checkbox {
			font-size: 36rpx;
			margin-left: 10rpx;
		}

		.checked {
			color: $color-primary;
		}
	}

	.pay-box {
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
		height: 100rpx;
	}

	.modal-content {
		.change-address-btn {
			line-height: 2;
			padding: 0 1em;
		}

		.pay_btn {
			width: 100%;
			border-radius: 50rem !important;
			line-height: 3;
		}
	}

	.scan-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.scan-icon-left {
		width: 50rpx;
		height: 50rpx;
	}

	.scan-btn {
		border: none !important;
		background: #fff;
	}
</style>